package com.hc.testaudio.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.yc.yclibrary.YcInit;
import com.yc.yclibrary.exception.ApiException;
import com.yc.yclibrary.exception.ErrorType;
import com.yc.yclibrary.net.BaseObserver;
import com.yc.yclibrary.utils.ActivityUtils;
import com.yc.yclibx.comment.YcLog;

import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 *
 */

public abstract class NetObserver<T extends HttpResponse> extends BaseObserver<T> {
    private Disposable mDisposable;

    public NetObserver() {
    }

    @Override
    public void onSubscribe(Disposable d) {
        mDisposable = d;
        if (!isNetworkAvailable()) {
            YcLog.e("网络不可用");
            ActivityUtils.INSTANCE.getCurrentActivity().showToast("哎呀，网络开小差啦~");
            onFail(new ApiException("网络不可用", ErrorType.NETWORK_ERROR));
            mDisposable.dispose();
        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager) YcInit.getContext().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (null == manager)
            return false;
        NetworkInfo info = manager.getActiveNetworkInfo();
        return null != info && info.isAvailable();
    }

    public void cancel() {
        if (mDisposable != null)
            mDisposable.dispose();
    }

    @Override
    public void onNext(@NonNull T response) {
        //防止闪退问题
        try {
            if (response.getCode() == 1) {
                super.onNext(response);
            } else {
                onFail(new ApiException(response.getMsg(), response.getCode()));
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            Log.e("", "网络异常！错误码:" + ErrorType.DATE_NULL);
        } catch (ApiException e) {
            e.printStackTrace();
            Log.e("", "网络异常！错误码:" + e.getCode() + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("", "网络异常！错误码:" + response.getCode());
        }
    }
}
